import { useCookie } from "./useCookie";
/**
 *
 * @param {string} type sessionStorage、localStorage、sessionStorage, cookie
 * @returns
 */
export function useStorage(type) {
  const cookies = useCookie();

  const setStorage = (key, value) => {
    if (type === "cookie") {
      cookies.setCookie(
        key,
        typeof value === "object" || Array.isArray(value)
          ? JSON.stringify(value)
          : value
      );
    } else {
      window[type].setItem(
        key,
        typeof value === "object" || Array.isArray(value)
          ? JSON.stringify(value)
          : value
      );
    }
  };

  const getStorage = (key) => {
    if (type === "cookie") {
      const value = cookies.getCookie(key);
      try {
        return JSON.parse(value || "");
      } catch (error) {
        return value;
      }
    } else {
      const value = window[type].getItem(key);
      try {
        return JSON.parse(value || "");
      } catch (error) {
        return value;
      }
    }
  };

  const removeStorage = (key) => {
    if (type === "cookie") {
      cookies.setCookie(key, "", -1);
    } else {
      window[type].removeItem(key);
    }
  };

  const clear = () => {
    if (type === "cookie") {
      cookies.clear();
    } else {
      window[type].clear();
    }
  };

  return {
    setStorage,
    getStorage,
    removeStorage,
    clear,
  };
}
